package com.mostka.rpc.server;

import java.io.IOException;

import org.eclipse.jetty.websocket.WebSocket;

public class Socket implements WebSocket.OnTextMessage {

	private TextMessageHandler messageHandler;
	private String channel;
	private Connection _connection;
	private int token;
	private String hashClassName;

	public Socket(TextMessageHandler messageHandler, String channel, String hashClassName) {
		this.messageHandler = messageHandler;
		this.channel = channel;
		this.hashClassName = hashClassName;
		token = this.hashCode();
	}
	
	@Override
	public void onClose(int closeCode, String message) {
		messageHandler.onClose(token, channel);
	}

	@Override
	public void onOpen(Connection connection) {
		_connection = connection;
		messageHandler.onJoin(this, token, channel, hashClassName);
	}

	@Override
	public void onMessage(String data) {
		messageHandler.onMessage(token, channel, data);
	}

	public static int CLOSE_BAD_HASH=10001;
	public static int CLOSE_SERVER_CRASH=10002;
    /** Close the connection with specific closeCode and message.
     * @param closeCode The close code to send, or -1 for no close code
     * @param message The message to send or null for no message
     */
	public void close(int closeCode,String message){
		_connection.close(closeCode, message);
	}
	
	public void send(String message){
		if (_connection.isOpen()){
			try {
				_connection.sendMessage(message);
			} catch (IOException e) {}
		}
	}

	public boolean isOpen() {
		return _connection.isOpen();
	}
	
}
